package cn.wonderland.system.service.impl;

import cn.wonderland.system.domain.Menu;
import cn.wonderland.system.service.IMenuService;
import cn.wonderland.basic.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wonderland
 * @since 2023-05-10
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Override
    public List<Menu> first() {
        return super.findAll().stream().filter(menu -> Objects.nonNull(menu)
                && menu.getParentId() == null).collect(Collectors.toList());
    }

    @Override
    public List<Menu> menuTree() {
        List<Menu> result = new ArrayList<>();

        List<Menu> menuList = this.findAll();

        Map<Long, Menu> menuMap = menuList.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));

        menuList.forEach(menu -> {
            if (menu.getParentId() == null) {
                result.add(menu);
            } else {
                Menu parent = menuMap.get(menu.getParentId());
                if (parent!= null) {
                    parent.getChildren().add(menu);
                }
            }
        });
        return result;
    }
}
